document.addEventListener('DOMContentLoaded', function () {
    const tableBody = document.getElementById('broker-table-body');
    const refreshStatusEl = document.getElementById('refresh-status');

    // 获取i18n文本的辅助函数
    const getI18nText = (key, fallback) => {
        const element = document.querySelector(`[data-i18n="${key}"]`);
        return element ? element.textContent : fallback;
    };

    const updateBrokerTable = async () => {
        try {
            const response = await fetch('/api/brokers');
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const brokers = await response.json();
            const isSingleNode = brokers.length === 1;
            
            // 添加调试信息
            console.log('Brokers data:', brokers);
            console.log('Is single node:', isSingleNode);
            
            // 详细检查每个broker的Leader状态
            brokers.forEach((broker, index) => {
                console.log(`Broker ${index}:`, {
                    address: broker.address,
                    metaLeader: broker.metaLeader,
                    dataLeader: broker.dataLeader,
                    status: broker.status
                });
            });

            // 清空现有表格内容
            tableBody.innerHTML = '';

            // 根据新数据重新构建表格行
            brokers.forEach(broker => {
                // 获取i18n文本
                const metaLeaderText = getI18nText('brokers.meta.leader', 'Meta Leader');
                const dataLeaderText = getI18nText('brokers.data.leader', 'Data Leader');
                const initializingText = getI18nText('brokers.initializing', 'Initializing...');
                const followerText = getI18nText('brokers.follower', 'Follower');
                const aliveText = getI18nText('brokers.status.alive', 'ALIVE');
                
                // 【修复】改进单节点时的状态显示逻辑
                let rolesHtml = '';
                if (broker.metaLeader) {
                    rolesHtml += `<span class="badge bg-primary me-1">${metaLeaderText}</span>`;
                }
                if (broker.dataLeader) {
                    rolesHtml += `<span class="badge bg-info text-dark me-1">${dataLeaderText}</span>`;
                }

                if (isSingleNode && !broker.metaLeader && !broker.dataLeader) {
                    rolesHtml += `<span class="badge bg-warning text-dark">${initializingText}</span>`;
                } else if (!isSingleNode && !broker.metaLeader && !broker.dataLeader) {
                    rolesHtml += `<span class="badge bg-secondary">${followerText}</span>`;
                }

                const row = `
                    <tr>
                        <td>${broker.address}</td>
                        <td>${rolesHtml}</td>
                        <td><span class="badge bg-success">${aliveText}</span></td>
                    </tr>
                `;
                tableBody.insertAdjacentHTML('beforeend', row);
            });

            // 更新状态指示器为“成功”
            const liveUpdateText = getI18nText('dashboard.live.update', 'Live Update');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-success" role="status" aria-hidden="true"></span> ' + liveUpdateText;
        } catch (error) {
            console.error('Failed to fetch broker data:', error);
            // 更新状态指示器为“失败”
            const updateFailedText = getI18nText('brokers.update.failed', 'Update Failed');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-danger" role="status" aria-hidden="true"></span> ' + updateFailedText;
        }
    };

    // 每 5 秒刷新一次
    setInterval(updateBrokerTable, 5000);
});